package com.jiang.demo2;
//-- App.java


import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import com.alibaba.edas.acm.listener.ConfigChangeListener;
import com.alibaba.edas.acm.ConfigService;
import com.alibaba.edas.acm.exception.ConfigException;

public class App {

    private static Properties appCfg = new Properties();

    public static void initAndWatchConfig() {
        final String dataId = "jiangdemo";
        final String group = "DEFAULT_GROUP";
        final long timeoutInMills = 3000;

        // 从控制台命名空间管理中拷贝对应值
        Properties properties = new Properties();
        properties.put("endpoint", "acm.aliyun.com");
        properties.put("namespace", "8fad1262-cf9f-4399-b516-4bc251d04b9f");
        properties.put("accessKey", "048452ecd0e84747834c679f3c0c18c3");
        properties.put("secretKey", "f+b8/d0X3uZbkaebwpZC1PnBZl8=");

        // 如果是加密配置，则添加下面两行进行自动解密
        // properties.put("openKMSFilter", true);
        // properties.put("regionId", "$regionId");

        ConfigService.init(properties);

        // 直接获取配置内容
        try {
            String configInfo = ConfigService.getConfig(dataId, group, timeoutInMills);
            appCfg.load(new StringReader(configInfo));
        } catch (ConfigException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 监听配置变化，获取最新推送值
        ConfigService.addListener(dataId, group, new ConfigChangeListener() {
            public void receiveConfigInfo(String configInfo) {
                try {
                    appCfg.load(new StringReader(configInfo));
                } catch (Exception e) {
                    // process exception
                }
                refreshApp();
            }
        });
    }

    public static void refreshApp() {
        System.out.println("current thread pool size: " + appCfg.getProperty("threadPoolSize"));
        System.out.println("current log level: " + appCfg.getProperty("logLevel"));
        System.out.println("");
    }

    public static void main(String[] args) {
        initAndWatchConfig();

        // 让主线程不退出
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}
